package cc.smarnet.caihou.phone.taginfolists;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import cc.smarnet.caihou.IPConfig;
import cc.smarnet.caihou.R;
import cc.smarnet.caihou.adapter.SpacesItemDecoration;
import cc.smarnet.caihou.adapter.TaginfoAdapter;

import cc.smarnet.caihou.entity.TagInfo;
import cc.smarnet.caihou.phone.bracts.BractsActivity;
import cc.smarnet.caihou.util.CommonUtils;
import cc.smarnet.caihou.util.JSONArrayUtil;
import okhttp3.Call;

/**
 * 标签台账信息的activity
 */
public class TaginfoListActivity extends AppCompatActivity {
    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private LinearLayout failLoadLinearLayout;
    private LinearLayout noDataLinearLayout;
    private ProgressBar progressBar;
    private ImageButton imageButton;
    private Button addButton;

    private String token;

    private int pageNo = 1;// 取数分页的开始页
    private int pageSize = 5;// 每次取数的数量

    List<TagInfo> taginfoList = new ArrayList<>();
    TaginfoAdapter taginfoAdapter;


    String listUrl = IPConfig.baseUrl + "/flower/tagInfo/list";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_taginfo_list);

        getSupportActionBar().hide();//隐藏标题栏

        initViews();
        noDataLinearLayout.setVisibility(View.GONE);// 隐藏暂无数据的信息
        failLoadLinearLayout.setVisibility(View.GONE);// 隐藏数据加载失败的信息

        getToken();
        getTagInfo();
        // 点击返回按钮的监听
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 点击新增按钮的监听
//        addButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(TaginfoListActivity.this, BractsAddActivity.class);
//                startActivity(intent);
//            }
//        });
        //设置layoutManager,可以设置显示效果，是线性布局、grid布局，还是瀑布流布局(参数是：上下文、列表方向（横向还是纵向）、是否倒叙)
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new SpacesItemDecoration(20));// 设置item的上下左右边距
        recyclerView.setHasFixedSize(true);
        // 这里使用适配器的目的在于使系统不再报‘E/RecyclerView: No adapter attached; skipping layout’的错误
        /*List<Bracts> nullList=new ArrayList<>();
        taginfoAdapter=new taginfoAdapter(nullList);
        recyclerView.setAdapter(taginfoAdapter);*/

        // 上拉刷新，目前在此就不做业务处理了，因为初始时加载的那几条数据就是从第一条开始的查询的
        refreshLayout.setOnRefreshListener(new OnRefreshListener() { //下拉刷新
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh();
            }
        });

        //上拉加载更多
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(final RefreshLayout refreshlayout) {
                getTagInfo();
                refreshlayout.finishLoadMore(0);
            }
        });
    }

    public void initViews() {
        refreshLayout = findViewById(R.id.taginfo_refreshLayout);
        recyclerView = findViewById(R.id.taginfo_recyclerView);
        failLoadLinearLayout = findViewById(R.id.taginfo_failLoad_linearLayout);
        noDataLinearLayout = findViewById(R.id.taginfo_noData_linearLayout);
        progressBar = findViewById(R.id.taginfo_progressBar);
        imageButton = findViewById(R.id.taginfo_return);
//        addButton = findViewById(R.id.taginfo_add_button);
    }

    public void getToken() {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        token = sp.getString("token", null);
    }


    //加载列表数据
    public void getTagInfo() {
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .addParams("pageNo", String.valueOf(pageNo))
                .addParams("pageSize", String.valueOf(pageSize))
                .url(listUrl)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        failLoadLinearLayout.setVisibility(View.VISIBLE);// 显示数据加载失败的信息
                    }

                    @Override
                    public void onResponse(String response, int ID) {
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        failLoadLinearLayout.setVisibility(View.GONE);// 隐藏数据加载失败的信息
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            String records = JSON.parseObject(result).getString("records");
//                            // 按照harvestTime排序,之前的数据是按照harvestTime升序排序，排序后是按照harvestTime降序排序
//                            String newRecords = JSONArrayUtil.jsonArraySort(records);
                            JSONArray jsonArray = JSON.parseArray(records);
                            // 获取标签信息并存到taginfoList中
                            for (int i = 0; i < jsonArray.size(); i++) {
                                String id = "";
                                String baseName = "";// 来源基地
                                String greenhouseName = "";// 来源大棚
                                String variety = "";// 采收品种
                                String varietyCode = "";// 采收品种
                                String sorter = "";// 分拣员
                                String sortTime = "";// 分拣日期
                                String packingSpecifications = "";// 打包规格
                                String classes = "";// 等级
                                String flowerPoleLength = "";// 花杆长度
                                String state = "-1";// 状态: 新增(-1),已打印标签(0),入库(1),出库(2)
                                String stockOutTime = "";//出库时间
                                String stockInTime = "";//入库时间
                                String stockOutUser = "";//出库人
                                String stockInUser = "";//入库人


                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                if (jsonObj.containsKey("id")) {
                                    id = jsonObj.getString("id");
                                }
                                if (jsonObj.containsKey("baseName")) {
                                    baseName = jsonObj.getString("baseName");// 来源基地
                                }
                                if (jsonObj.containsKey("greenhouseName")) {
                                    greenhouseName = jsonObj.getString("greenhouseName");// 来源大棚
                                }
                                if (jsonObj.containsKey("variety")) {
                                    variety = jsonObj.getString("variety");//
                                }if (jsonObj.containsKey("varietyCode")) {
                                    varietyCode = jsonObj.getString("varietyCode");//
                                }
                                if (jsonObj.containsKey("sorter")) {
                                    sorter = jsonObj.getString("sorter");//
                                }
                                if (jsonObj.containsKey("sortTime")) {
                                    sortTime = jsonObj.getString("sortTime");//
                                }
                                if (jsonObj.containsKey("packingSpecifications")) {
                                    packingSpecifications = jsonObj.getString("packingSpecifications");//
                                }
                                if (jsonObj.containsKey("classes")) {
                                    classes = jsonObj.getString("classes");//
                                }
                                if (jsonObj.containsKey("flowerPoleLength")) {
                                    flowerPoleLength = jsonObj.getString("flowerPoleLength");//
                                }
                                if (jsonObj.containsKey("state")) {
                                    state =    CommonUtils.getState(jsonObj.getString("state"));//
                                }
                                if (jsonObj.containsKey("stockOutTime")) {
                                    stockOutTime = jsonObj.getString("stockOutTime");//
                                }
                                if (jsonObj.containsKey("stockInTime")) {
                                    stockInTime = jsonObj.getString("stockInTime");//
                                }
                                if (jsonObj.containsKey("stockOutUser")) {
                                    stockOutUser = jsonObj.getString("stockOutUser");//
                                }
                                if (jsonObj.containsKey("stockInUser")) {
                                    stockInUser = jsonObj.getString("stockInUser");//
                                }

                                TagInfo tagInfo = new TagInfo();

                                tagInfo.setId(id);
                                tagInfo.setSourceBase(baseName);
                                tagInfo.setSourceGreenhouse(greenhouseName);
                                tagInfo.setVariety(variety);
                                tagInfo.setVarietyCode(varietyCode);
                                tagInfo.setSorter(sorter);
                                tagInfo.setSortTime(sortTime);
                                tagInfo.setPackingSpecifications(packingSpecifications);
                                tagInfo.setClasses(classes);
                                tagInfo.setFlowerPoleLength(flowerPoleLength);
                                tagInfo.setState(state);
                                tagInfo.setStockOutTime(stockOutTime);
                                tagInfo.setStockInTime(stockInTime);
                                tagInfo.setStockOutUser(stockOutUser);
                                tagInfo.setStockInUser(stockInUser);

                                taginfoList.add(tagInfo);
                            }
                            if (taginfoList.size() > 0) {// 如果taginfoList中有数据的话就通过taginfoAdapter将数据显示在界面上
                                taginfoAdapter = new TaginfoAdapter(getApplicationContext(), taginfoList);
                                recyclerView.setAdapter(taginfoAdapter);
                            } else {// 否则让暂无数据的信息显示在界面上
                                noDataLinearLayout.setVisibility(View.VISIBLE);
                            }

                            int total=Integer.valueOf(JSON.parseObject(result).getString("total"));//数据在数据库中的总数
                            int current=Integer.valueOf(JSON.parseObject(result).getString("current"));//该次取数是第几次
                            if (current*pageSize>=total){
                                Toast.makeText(TaginfoListActivity.this, "已加载完所有数据", Toast.LENGTH_SHORT).show();
                            }

                            pageNo += 1;
                        }
                    }
                });
    }
}